<?php

namespace App\Models;

use App\Events\RepayMentEvent;
use App\Exceptions\GeneralException;
use App\Jobs\RepayMoneyNotifyJobQueue;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 * App\Models\RepayRecordCommon
 *
 * @property int $id
 * @property int $uid 关联用户id
 * @property int $summary_id 关联还款表id
 * @property int $record_id 关联还款记录表id
 * @property int $bank_cards_id 关联user_bank_cards银行卡id
 * @property string $trade_no 平台内唯一流水号
 * @property int $period 当前期数,0为全部还清记录
 * @property int $lending_money 利息费,以分为单位
 * @property int $fines_money 罚息费,以分为单位
 * @property int $manage_money 贷后管理费,以分为单位
 * @property int $repayment_money 提前还款手续费,以分为单位
 * @property int $failure 失败原因, 枚举
 * @property int $status 蔚捷接口状态 1:待处理,2:处理中,3:失败,4:成功
 * @property \Illuminate\Support\Carbon|null $created_at
 * @property \Illuminate\Support\Carbon|null $updated_at
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\RepayRecordCommon newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\RepayRecordCommon newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\RepayRecordCommon query()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\RepayRecordCommon whereBankCardsId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\RepayRecordCommon whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\RepayRecordCommon whereFailure($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\RepayRecordCommon whereFinesMoney($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\RepayRecordCommon whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\RepayRecordCommon whereLendingMoney($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\RepayRecordCommon whereManageMoney($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\RepayRecordCommon wherePeriod($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\RepayRecordCommon whereRecordId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\RepayRecordCommon whereRepaymentMoney($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\RepayRecordCommon whereStatus($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\RepayRecordCommon whereSummaryId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\RepayRecordCommon whereTradeNo($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\RepayRecordCommon whereUid($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\RepayRecordCommon whereUpdatedAt($value)
 * @mixin \Eloquent
 * @property string $third_record_id 资方接口返回,公共请求id
 * @property string|null $apply_time 接口申请时间
 * @property string|null $status_time 接口处理成功/失败时间
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\RepayRecordCommon whereApplyTime($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\RepayRecordCommon whereStatusTime($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\RepayRecordCommon whereThirdRecordId($value)
 * @property-read \App\Models\RepayRecord $record
 * @property-read \App\Models\UserCertOcr $relationUserCertOcrs
 * @property-read \App\Models\User $relationUsers
 * @property int $repay_type 1=>app中用户手动点击还款,2=>app中自动还款
 * @property-read \App\Models\RepayRecordMoney $money
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\RepayRecordCommon whereRepayType($value)
 */
class RepayRecordCommon extends Model
{
    //蔚捷公共接口状态 1:待处理,2:处理中,3:失败,4:成功
    const STATUS_ONE = 1;
    const STATUS_TWO = 2;
    const STATUS_THREE = 3;
    const STATUS_FOUR = 4;

    //通知资方的状态
    const MONEY_NOTIFY_STATUS_ONE = 1;
    const MONEY_NOTIFY_STATUS_TWO = 2;
    const MONEY_NOTIFY_STATUS_THREE = 3;
    const MONEY_NOTIFY_STATUS_FOUR = 4;

    //公共平台的扣费字段传后缀
    const COMMON_PREFIX = 'K2';
    const OLD_COMMON_PREFIX = 'K1';

    //公共平台的第三方字段,公共支付成功后的三方字段固定值
    const THIRD_RECORD_ID = 'JD_WITHHOLD';
    //公共平台的商户号
    const NEW_COMMON_MER = 'lianzhong';
    const OLD_COMMON_MER = 'weishang';

    /**
     * 不可被批量赋值的属性。
     *
     * @var array
     */
    protected $guarded = [];

    /**
     * Description: 设置资方记录利息费
     * Author: Gxs
     * @param $value
     */
    public function setLendingMoneyAttribute($value)
    {
        $this->attributes['lending_money'] = (int)bcmul($value, 100);
    }

    /**
     * Description: 获取资方记录利息费
     * Author: Gxs
     * @param $value
     * @return int
     */
    public function getLendingMoneyAttribute($value)
    {
        return bcdiv($value, 100, 2);
    }

    /**
     * Description: 设置资方记录罚息费
     * Author: Gxs
     * @param $value
     */
    public function setFinesMoneyAttribute($value)
    {
        $this->attributes['fines_money'] = (int)bcmul($value, 100);
    }

    /**
     * Description: 获取资方记录罚息费
     * Author: Gxs
     * @param $value
     * @return int
     */
    public function getFinesMoneyAttribute($value)
    {
        return bcdiv($value, 100, 2);
    }

    /**
     * Description: 设置资方记录贷后管理费
     * Author: Gxs
     * @param $value
     */
    public function setManageMoneyAttribute($value)
    {
        $this->attributes['manage_money'] = (int)bcmul($value, 100);
    }

    /**
     * Description: 获取资方记录贷后管理费
     * Author: Gxs
     * @param $value
     * @return int
     */
    public function getManageMoneyAttribute($value)
    {
        return bcdiv($value, 100, 2);
    }

    /**
     * Description: 设置资方记录提前还款手续费
     * Author: Gxs
     * @param $value
     */
    public function setRepaymentMoneyAttribute($value)
    {
        $this->attributes['repayment_money'] = (int)bcmul($value, 100);
    }

    /**
     * Description: 获取资方记录提前还款手续费
     * Author: Gxs
     * @param $value
     * @return int
     */
    public function getRepaymentMoneyAttribute($value)
    {
        return bcdiv($value, 100, 2);
    }

    /**
     * Description: 设置减免金额
     * Author: ljf
     * @param $value
     */
    public function setReliefAmountAttribute($value)
    {
        $this->attributes['relief_amount'] = (int)bcmul($value, 100);
    }

    /**
     * Description: 获取减免金额
     * Author: ljf
     * @param $value
     * @return int
     */
    public function getReliefAmountAttribute($value)
    {
        return bcdiv($value, 100, 2);
    }


    /**
     * Description: 设置折扣金额
     * Author: ljf
     * @param $value
     */
    public function setDiscountAmountAttribute($value)
    {
        $this->attributes['discount_amount'] = (int)bcmul($value, 100);
    }
    /**
     * Description: 获取折扣金额
     * Author: ljf
     * @param $value
     * @return int
     */
    public function getDiscountAmountAttribute($value)
    {
        return bcdiv($value, 100, 2);
    }

    /**
     * Description: 关联记录表
     * Author: Gxs
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function record()
    {
        return $this->hasOne('App\Models\RepayRecord', 'id', 'record_id');
    }

    /**
     * Description: 关联资方表
     * Author: Gxs
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function money()
    {
        return $this->hasOne('App\Models\RepayRecordMoney', 'record_id', 'record_id');
    }

    /**
     * Description: 反关summary
     * Author: Gxs
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function relationSummary()
    {
        return $this->belongsTo('App\Models\RepaySummary', 'summary_id', 'id');
    }

    /**
     * Description: 反关用户表
     * Author: Gxs
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function relationUsers()
    {
        return $this->belongsTo('App\Models\User', 'uid', 'id');
    }

    /**
     * Description: 反关用户身份证实名表
     * Author: Gxs
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function relationUserCertOcrs()
    {
        return $this->belongsTo('App\Models\UserCertOcr', 'uid', 'user_id');
    }

    public function getLoanIdAttribute(){
        return \App\Models\RepaySummary::where('id',$this->summary_id)->value('loan_id');
    }

    /**
     * Description:公共结果查询成功,或者公共的金额为0 改变状态
     * Author:lijiafei
     * @param RepayRecordCommon $model
     * @param array $data
     * @throws GeneralException
     */
    public static function setCommonSuccessStatus(RepayRecordCommon $model,array $data = [])
    {
        try {
            DB::beginTransaction();
            if (0 == $model->period) {
                //全部还清
                //本队列对应的公共表
                $model::where([
                    ['summary_id', '=', $model->summary_id],
                    ['status', '<>', $model::STATUS_FOUR],
                ])->update([
                    'pay_order_no' => isset($data['payOrderNo']) ? $data['payOrderNo'] : '', //京东商户订单号
                    'manage_money' => 0, //提前结清的贷后管理费0
                    'failure' => '',//把以前的错误信息清空
                    'status' => $model::STATUS_FOUR,
                    'status_time' => Carbon::now(),
                ]);
                //最后顺序队列全部还清调用逻辑
                RepayRecord::setNormalAllPeriodSuccess($model);
            } else {
                //单期还清
                //本队列对应的公共表
                $model->update([
                    'pay_order_no' => isset($data['payOrderNo']) ? $data['payOrderNo'] : '', //京东商户订单号
                    'status' => $model::STATUS_FOUR,
                    'failure' => '',//把以前的错误信息清空
                    'status_time' => Carbon::now(),
                ]);

                //最后顺序队列单期还款调用逻辑
                RepayRecord::setNormalCurrentPeriodSuccess($model);
            }
            DB::commit();
            self::setMoneyNotify($model);
            event(new RepayMentEvent($model->summary_id));
        } catch (\Exception $e) {
            DB::rollBack();
            Log::debug('repay_get_common_result', ['message' => $e->getMessage(), 'line' => $e->getLine()]);
            throw new GeneralException($e->getMessage());
        }
    }

    public static function setMoneyNotify(RepayRecordCommon $model){
        $summaryInfo = $model->relationSummary;
        if($summaryInfo->loan_channel == SettingChannel::CHANNEL_OLD_GUANGDA && $summaryInfo->data_type == RepaySummary::DATA_TYPE_TWO){
            RepayMoneyNotifyJobQueue::dispatch($model->record->id);
        }
    }

    /**
     * Description:获取订单流水号结尾号
     * Author:lijiafei
     * @param $summaryInfo
     * @return string
     */
    public static function getBizOrderNoPrefix($summaryInfo){
        $prefix = $summaryInfo->data_type == RepaySummary::DATA_TYPE_ONE ? RepayRecordCommon::COMMON_PREFIX : RepayRecordCommon::OLD_COMMON_PREFIX;//区分业务订单前缀
        return $prefix;
    }

}